package com.cuanbobox.tcp.matrix;


import android.text.TextUtils;
import android.util.Log;

import com.cuanbobox.base.App;
import com.cuanbobox.bean.DataK200Bean;
import com.cuanbobox.bean.MatrixSlefCheckBean;
import com.cuanbobox.constant.MatrixConstant;
import com.cuanbobox.service.BackgroundService;
import com.cuanbobox.utils.BroadcastUtil;
import com.cuanbobox.utils.ConnectStateUtil;
import com.cuanbobox.utils.LogUtil;
import com.cuanbobox.utils.SharedPreferencesUtil;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * 接收矩阵消息的线程
 */
public class MatrixReceiveThread extends Thread {
    private MatrixInitThread tcpInitThread;
    private InputStream input;
    private String str_receive;
    private boolean loop;
    private String oldStrReceive;

    public MatrixReceiveThread(MatrixInitThread tcpInitThread) {
        this.tcpInitThread = tcpInitThread;
        try {
            input = tcpInitThread.getSocket().getInputStream();
        } catch (IOException e) {}
    }

    @Override
    public void run() {
        super.run();
        loop = true;
        LogUtil.add("接收", "启动接收线程-->" + Thread.currentThread().getName(), "矩阵");
        while (App.running && loop&&!App.debugMode) {
            try {
                //非阻塞接收数据，但数据大小有限制
                byte buffer[] = new byte[10240];
                int count = input.read(buffer);
                if (count != -1) {
                    ConnectStateUtil.recordTime(App.getInstance().getApplicationContext(), MatrixConstant.KEY_MATRIX);
                    str_receive = new String(buffer, 0, count, "utf-8");
                    if (App.readingMatrixInfo) {
                        try {
                            String str = "";
                            if (str_receive.contains("{\"system")) {
                                oldStrReceive = str_receive;
                            }
                            if (str_receive.contains("}]}}")) {
                                str = oldStrReceive + str_receive;
                            }
                            if(str_receive.contains("{\"system")&&str_receive.contains("}]}}")){
                                str=str_receive;
                            }
                            //if (Pattern.compile(".*\\{.*\\}.*").matcher(str).matches()) {
                                if (str.contains("MVP-K200")) {
                                    new Gson().fromJson(str, DataK200Bean.class);
                                }if (str.contains("MCH7000C")) {
                                    new Gson().fromJson(str, DataK200Bean.class);
                                } else if (str.contains("MVP-8C")) {
                                    new Gson().fromJson(str, MatrixSlefCheckBean.class);
                                } else if (str.contains("MVP-16C")) {
                                    new Gson().fromJson(str, MatrixSlefCheckBean.class);
                                } else if (str.contains("16C")) {
                                    new Gson().fromJson(str, MatrixSlefCheckBean.class);
                                } else if (str.contains("MAC-E1")) {
                                    new Gson().fromJson(str, MatrixSlefCheckBean.class);
                                }/* else {
                                    new Gson().fromJson(str, MatrixSlefCheckBean.class);
                                }*/
                                BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_READ_MATRIX_INFO_MSG_SUCCESS, str);
                            //}
                        } catch (Exception e) {
                            //LogUtil.addError(e);
                        }
                    }
                    BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_MSG, str_receive);
                }
            } catch (SocketException e) {
                LogUtil.addError(e);
                tcpInitThread.close();
                LogUtil.add("MatrixReceiveThread(168)","matrixTcpInitThread.close()","关闭中控Tcp");
                if (e.getMessage().contains("Socket") && e.getMessage().contains("closed")) {//当socket已关闭时，还做读写操作报该错误
                    //Log.i("MatrixReceiveThread", "当socket已关闭时，还做读写操作报该错误SocketException Socket closed!");
                } else {
                    e.printStackTrace();
                    BackgroundService.reConnectingMatrix = false;
                    BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_ERROR);
                }
            } catch (Exception e) {
                LogUtil.addError(e);
                tcpInitThread.close();
                LogUtil.add("MatrixReceiveThread(178)","matrixTcpInitThread.close()","关闭中控Tcp");
                BackgroundService.reConnectingMatrix = false;
                BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECEIVE_ERROR);
                e.printStackTrace();
            }
        }
        try {
            input.close();
        } catch (IOException e) {
        }
        LogUtil.add("接收", "关闭接收线程-->" + Thread.currentThread().getName(), "矩阵");
    }

    public void stopThread() {
        loop = false;
    }
}
